<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Usersauthority;
use App\Models\Miniappsauthorization;
use App\Models\Linkslistsminapps;
use App\Models\Users;
use App\Services\CacheService;
use App\Services\WechatopenService;
use App\Services\WechatsService;
use App\Services\WechatoffiaccountService;
use App\Services\WechattmplmsgService;
use App\Jobs\Miniappdisable;
use DB,Log,Exception;

class Minigetvisitstatus extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'miniapps:getvisitstatus';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '检测授权小程序服务状态（是否暂停服务,只检测私有使用小程序）';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->suspendAppids = [];
        $this->unAuthorAppids = [];
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        // miniapp_type 小程序类型:1.三方上架2.用户自有3.API获取Token4.扫码授权
        // visitstatus 上线状态:1.正常2.暂停服务3.程序异常4.封禁5.未检测
        // status 小程序类型:1.私有2.公用
        $time_start = time();
        DB::table("links_lists_minapps")->select('id','users_id','appid','name','miniapp_type')->whereIn('miniapp_type',[1,2,4])->where('visitstatus',1)->where('status',1)->groupBy('appid')->orderBy('id','ASC')->chunk(100, function($miniapps) {
            $openTypes = ["",1,3,"",2];
            // 扫码跳转的小程序没有检测权限,判断有没有开启授权
            $componentAppids = ["","wxa755405206410fd2","wxe7f72c27fd3683c6","","wxe7f72c27fd3683c6"];
            foreach ($miniapps as $miniapp) {
                // dump($miniapp->id);
                $open_type = $openTypes[$miniapp->miniapp_type];
                $component_appid = $componentAppids[$miniapp->miniapp_type];
                // 更新小程序的OpenType
                // Miniappsauthorization::updateMiniauthOpenType($miniapp->appid,$component_appid,$open_type);
                // 获取小程序授权信息
                $miniappAuth = Miniappsauthorization::getCompMiniappAuth($miniapp->appid,$component_appid);
                if (empty($miniappAuth)) {
                    // 没有获取到小程序授权信息,更新检测状态
                    $this->unAuthorAppids[] = $miniapp->appid;
                    // Linkslistsminapps::updateLinkListMiniappVisit($miniapp->id,5);
                } else {
                    try {                            
                        $access_token = WechatopenService::getMiniProgramAccessToken($miniappAuth->component_appid,$miniapp->appid,$miniappAuth->authorizer_refresh_token);
                        //根据第三方token检测小程序状态
                        $visitStatus = WechatsService::getvisitstatus($access_token);
                        if($visitStatus["errcode"] == 0){
                            // 获取检测结果成功
                            // status:0、表示已暂停服务（包含主动暂停服务违规被暂停服务）,1、表示未暂停服务。
                            if($visitStatus["status"] == 0){
                                $this->suspendAppids[] = $miniapp->appid;
                            } else {

                            }
                        } else {
                            if ($visitStatus["errcode"] == 61007) {
                                // 授权第三方没有api检测权限
                                $this->unAuthorAppids[] = $miniapp->appid;
                            }
                        }
                    } catch (Exception $e) {
                        // 未获取到小程序token
                        $this->unAuthorAppids[] = $miniapp->appid;
                    }
                }
            }
        });
        // if (!empty($this->suspendAppids)) {
        //     // 更新暂停服务列表小程序,改为到脚本执行
        //     DB::table("links_lists_minapps")->whereIn("appid",$this->suspendAppids)->update(["visitstatus"=>2,"disable"=>5]);
        // }
        if (!empty($this->unAuthorAppids)) {
            // 更新无法检测列表
            DB::table("links_lists_minapps")->whereIn("appid",$this->unAuthorAppids)->update(["visitstatus" => 3]);
        }
        // 自动切换微信小程序
        foreach ($this->suspendAppids as $suspendAppid) {
            Miniappdisable::dispatch($suspendAppid,2)->delay(10);
        }
        $diffTime = time()-$time_start;
        Log::info("执行时长:".$diffTime."秒");
    }
}
